﻿Imports System.Xml.Serialization

Namespace Commands

    Public Class GetSharedItemDetails
        Inherits Framework.Net.CommandBase

        Private Const mRequestCode As String = "GetSharedItemDetails"
        Private Const mReplyCode As String = "GetSharedItemDetailsReply"

        Public Sub New()
            MyBase.New(mRequestCode, mReplyCode)
        End Sub

        Public Class Request
            <XmlAttribute()> Public SharedItemId As Integer
        End Class
        Public Class Reply
            Public Item As Entities.SharedItem
            Public Files As Generic.List(Of Entities.SharedItemFile)
            Public MediaInfo As Entities.MediaInfo
        End Class

        Public Delegate Sub ReplyDelegate(ByVal inReplyToMessageId As Integer, ByVal node As Framework.Net.Node, ByVal reply As Reply)
        Public Shared Function SendRequest(ByVal node As Framework.Net.Node, ByVal sharedItemId As Integer, ByVal callback As ReplyDelegate, ByVal invokeCallbackOnMainGuiThread As Boolean) As Integer
            Dim clsRequest As New Request
            clsRequest.SharedItemId = sharedItemId

            Dim iMessageId As Integer = Framework.Net.Manager.GetNextMessageId()
            RegisterCallback(iMessageId, callback, invokeCallbackOnMainGuiThread)
            node.SendCommandMessageAsync(iMessageId, mRequestCode, Framework.Serialization.ToXmlBytes(clsRequest))
            Return iMessageId
        End Function

        Public Overrides Sub HandleReply(ByVal envelope As Framework.Net.MessageEnvelope)
            Dim clsReply As Reply = Framework.Serialization.FromXmlBytes(Of Reply)(envelope.Message.Message)
            InvokeCallback(envelope.Message.InReplyToId, envelope.Node, clsReply)
        End Sub


        Public Overrides Sub HandleRequest(ByVal envelope As Framework.Net.MessageEnvelope)
            Dim clsReq As Request = Framework.Serialization.FromXmlBytes(Of Request)(envelope.Message.Message)

            Dim clsReply As New Reply

            Dim clsItem As Entities.SharedItem = EntityHandlers.SharedItems.GetById(clsReq.SharedItemId)
            If envelope.Node.BuddyKeyMaster.IsGranted(clsItem) Then
                clsReply.Item = clsItem
                clsReply.Files = EntityHandlers.SharedItemsFiles.GetAllBySharedItemId(clsReq.SharedItemId)
                clsReply.MediaInfo = EntityHandlers.MediaInfo.GetBySharedItemId(clsReq.SharedItemId)
            End If

            envelope.Node.SendReplyCommandMessageAsync(envelope, mReplyCode, Framework.Serialization.ToXmlBytes(clsReply))
        End Sub
    End Class

End Namespace
